package com.enjoylearning.media.service.impl;

import com.enjoylearning.media.mapper.MediaFilesMapper;
import com.enjoylearning.media.mapper.MediaProcessHistoryMapper;
import com.enjoylearning.media.mapper.MediaProcessMapper;
import com.enjoylearning.media.model.po.MediaFiles;
import com.enjoylearning.media.model.po.MediaProcess;
import com.enjoylearning.media.model.po.MediaProcessHistory;
import com.enjoylearning.media.service.MediaFileProcessService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MediaFileProcessServiceImpl implements MediaFileProcessService {

    @Autowired
    MediaProcessMapper mediaProcessMapper;
    @Autowired
    private MediaFilesMapper mediaFilesMapper;
    @Autowired
    private MediaProcessHistoryMapper mediaProcessHistoryMapper;

    @Override
    public List<MediaProcess> getMediaProcessList(Integer shardTotal, Integer shardIndex, Integer count) {
        return mediaProcessMapper.selectListByShardingIndex(shardTotal, shardIndex, count);
    }

    @Override
    public Boolean startTask(Long id) {
        Integer i = mediaProcessMapper.startTask(id);
        return i > 0;
    }

    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errMsg) {
        //要更新的任务
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if (mediaProcess == null) {
            return;
        }
        //任务执行失败
        if (status.equals("3")){
            mediaProcess.setStatus("3");
            mediaProcess.setFailCount(mediaProcess.getFailCount() + 1);
            mediaProcess.setErrormsg(errMsg);
            mediaProcessMapper.updateById(mediaProcess);
            return;
        }
        //任务执行成功
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        //更新media中的url
        mediaFiles.setUrl(url);
        mediaFilesMapper.updateById(mediaFiles);
        //更新mediaProcess的状态
        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcess.setUrl(url);
        mediaProcessMapper.updateById(mediaProcess);
        //将任务记录插入到mediaProcessHistory表
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistoryMapper.insert(mediaProcessHistory);
        //从mediaProcess删除当前的任务
        mediaProcessMapper.deleteById(taskId);
    }


}
